package com.tac.common.interceptor;

import com.tac.common.myException.CustomException;
import com.tac.common.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class CheckTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截到请求地址：{}，的{}请求",request.getRemoteAddr(),request.getRequestURI());
        String method = request.getMethod();
        if(method.equalsIgnoreCase("options")){
            log.info("options放行");
           return true;
        }
        String token = request.getHeader("token");
        if(token==null){
            throw new CustomException("token不能为空");
        }
        JwtParser parser = Jwts.parser();
        parser.setSigningKey("tac666");
        try{
            Jws<Claims> claimsJws = parser.parseClaimsJws(token);
            Claims body = claimsJws.getBody();
            String s = body.getSubject();
            UserThreadLocal.setId(Integer.parseInt(s));
            return true;
        }catch (Exception e){
            throw new CustomException("token有误");
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.removoId();
    }
}
